package br.edu.unibratec.viagemfacil;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class FraseParser {

	public static List<Frase> recuperarFrases() throws Exception{
		
		URL url = new URL("https://dl.dropboxusercontent.com/s/1gkiv479iuriksh/" +
				"viagemFacil.json");
		HttpURLConnection conexao = (HttpURLConnection)url.openConnection();
		conexao.setRequestMethod("GET");
		conexao.setReadTimeout(10000);
		conexao.setConnectTimeout(15000);
		conexao.setDoInput(true);
		
		conexao.connect();
		if (conexao.getResponseCode() == 200){
			return parseFrasesJson(conexao.getInputStream());
		}
		return null;
	}

	private static List<Frase> parseFrasesJson(InputStream inputStream) 
			throws JSONException, Exception {
		
		List<Frase> frases = new ArrayList<Frase>();
		
		JSONObject json = new JSONObject(streamToString(inputStream));
		JSONArray jsonPosts = json.getJSONArray("Frases");
		for (int i = 0; i < jsonPosts.length(); i++) {
			JSONObject jsonFrase = jsonPosts.getJSONObject(i);
			String fraseOriginal     = jsonFrase.getString("FraseOriginal");
			String fraseTraduzida    = jsonFrase.getString("FraseTraduzida");
			
			Frase frase = new Frase(fraseOriginal, fraseTraduzida);
			frases.add(frase);
		}
		return frases;
	}
	
	private static String streamToString(InputStream inputStream) throws Exception {
		BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
		
		StringBuilder sBuffer = new StringBuilder();
		
		String line = null;
		while ((line = reader.readLine()) != null) {
			sBuffer.append(line);
		}
		inputStream.close();
		return sBuffer.toString();
	}
}